<template>
  <el-dialog v-model="dialogVisible" title="分配负责人" width="500px" :close-on-click-modal="false">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="前端负责人" prop="frontend">
        <user-select v-model="form.frontend" placeholder="请选择前端负责人" />
      </el-form-item>
      <el-form-item label="后端负责人" prop="backend">
        <user-select v-model="form.backend" placeholder="请选择后端负责人" />
      </el-form-item>
      <el-form-item label="测试负责人" prop="test">
        <user-select v-model="form.test" placeholder="请选择测试负责人" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import userSelect from "@/components/SelectFilter/user-select.vue";
import { SprintBoard } from "../types/sprintBoard";

interface Props {
  visible: boolean;
  assignees: SprintBoard.AssigneeInfo;
}

interface Emits {
  (e: "update:visible", value: boolean): void;
  (e: "confirm", assignees: SprintBoard.AssigneeInfo): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const dialogVisible = ref(false);

const formRef = ref<FormInstance>();

const form = reactive<SprintBoard.AssigneeInfo>({
  frontend: "",
  backend: "",
  test: ""
});

const rules = {
  // 可以根据需要添加验证规则
};

// 监听visible变化
watch(
  () => props.visible,
  newVal => {
    dialogVisible.value = newVal;
    if (newVal) {
      // 重置表单
      form.frontend = props.assignees.frontend || "";
      form.backend = props.assignees.backend || "";
      form.test = props.assignees.test || "";
    }
  }
);

// 监听dialogVisible变化
watch(dialogVisible, newVal => {
  if (!newVal) {
    emit("update:visible", false);
  }
});

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false;
};

// 处理确认
const handleConfirm = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    emit("confirm", { ...form });
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error("请检查输入信息");
  }
};
</script>

<style lang="scss" scoped>
// 样式可以根据需要添加
</style>
